<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="职务名称">
        <el-input
          v-model="queryConditions.name"
          style="width: 200px"
          size="large"
          placeholder="请输入职务名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="所属部门">
        <el-input
          v-model="queryConditions.department"
          style="width: 200px"
          size="large"
          placeholder="请输入所属部门"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表组件，监听分页、操作和编辑事件 -->
    <TestPage
      :table-data="formattedTableData"
      :columns="tableColumns"
      :current-page="pageNo"
      :total="allPage"
      :page-size="pageSize"
      @page-change="handlePageChange"
      @action="handleTableAction"
      @edit="openEditDialog"
      @delete="handleDelete"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive,computed } from 'vue'
import request from '@/util/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import type { Role } from '@/types/rs/Role'
import { useRouter } from 'vue-router'

// 分页与查询状态
type Query = { name: string; department: string }
const pageNo = ref(1)
const pageSize = ref(10)
const allPage = ref(0)
const queryConditions = reactive<Query>({ name: '', department: '' })

// 列配置
const tableColumns = ref([
  { prop: 'id', label: '职务 ID' },
  { prop: 'name', label: '职务名称' },
  { prop: 'is_delete', label: '删除状态' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }
])

// 表格数据
const tableData = ref<Role[]>([])
  const formattedTableData = computed(() =>
  tableData.value.map(item => ({
    ...item,
    is_delete: item.is_delete === 0 ? '正常' : '被删除'
  }))
)
const router = useRouter()

// 查询方法
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams()
    params.append('pageNow', page.toString())
    params.append('pageSize', pageSize.value.toString())
    params.append('name', queryConditions.name)
    params.append('department', queryConditions.department)

    const resp = await request.post('per/role/getPage', params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    const d = resp.data.data
    console.log(d)
    tableData.value = d.list || []
    allPage.value = d.total || 0
  } catch (error) {
    ElMessage.error('获取职务数据失败')
    tableData.value = []
    allPage.value = 0
    console.error('获取数据失败：', error)
  }
}

// 分页变化
function handlePageChange(newPage: number) {
  pageNo.value = newPage
  fetchData(newPage)
}

// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'AddRole' })
  }
}

// 编辑
function openEditDialog(row: Role) {
  router.push({ name: 'EditRole', params: { id: row.id } })
}

// 删除
async function handleDelete(row: Role) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该职务吗？此操作不可恢复！',
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    await request.post('per/role/del', { id: row.id }, {
      headers: { 'Content-Type': 'application/json' }
    })
    ElMessage.success('删除成功')
    fetchData(pageNo.value)
  } catch (err: any) {
    if (err !== 'cancel') ElMessage.error('删除操作失败或发生错误')
  }
}

// 重置条件
function reset() {
  queryConditions.name = ''
  queryConditions.department = ''
  fetchData(1)
}

// 初始化
fetchData(1)
</script>

<style scoped>
.mb-4 { margin-bottom: 16px; }
</style>